package com.saoft.fangcms.web.tags;

import com.saoft.fangcms.web.util.DictUtil;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

public class SaoftDictTag extends SimpleTagSupport {

    private String attr;
    private String name;
    private String value;

    public void setName(String name) {
        this.name = name;
    }

    public void setAttr(String attr) {
        this.attr = attr;
    }

    public void setValue(String value) {
        this.value = value;
    }

    StringWriter sw = new StringWriter();

    @Override
    public void doTag() throws JspException, IOException {

        Map<String, String> valueList = DictUtil.value(attr);
        if(valueList != null && valueList.size() > 0) {


            StringBuilder optionContent = new StringBuilder();
            valueList.forEach((key, val) -> {
                optionContent.append("<option value = '").append(key);
                if(String.valueOf(key).equals(value)){
                    optionContent.append("' ").append("selected='selected");
                }
                optionContent.append("'>").append(val).append("</option>");
            });

            JspWriter out = getJspContext().getOut();
            JspFragment jspBody = getJspBody();
            if (jspBody != null) {
                jspBody.invoke(sw);
            }

            StringBuffer select = new StringBuffer();
            select.append("<select name='"+name+"' class='timo-search-select'>");
            select.append(sw);
            select.append(optionContent);
            select.append("</select>");
            out.println(select);
        }
    }
}
